package cn.kgc.spring01.factory;

import cn.kgc.spring01.mapper.NewUserMapperImpl;
import cn.kgc.spring01.mapper.UserMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author: mosin
 * @version: v1.0  2022/11/28
 * 获取类对象的工厂对象
 */
public class BeanFactory {

    // 存储初始化对象  单例
    private static Map<String,Object> beans = new HashMap<>();

    // 对象初始化  存储
    static {
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("Bean.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取所有的key  以及value 创建对象并保存
        Enumeration<Object> keys = properties.keys();
        while (keys.hasMoreElements()){
            String key = (String) keys.nextElement();
            String className = properties.getProperty(key);

            //通过反射创建对象
            try {
                Class<?> clazz = Class.forName(className);
                Object o = clazz.newInstance();
                beans.put(key, o);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    public static UserMapper getUserMapper() {

        return new NewUserMapperImpl();

    }

    // 反射方式   beanName  全限定名  包名+类名
    public static UserMapper getUserMapper(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            UserMapper userMapper  = (UserMapper) clazz.newInstance();
            return userMapper;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 通用的获取bean实例的方法
    public static Object getBean(String className) {
        try {
             Class<?> clazz = Class.forName(className);
             Object o =  clazz.newInstance();
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //重载的方法  通过指定 bean名字 和类型获取对象
    public static <T> T getBean(String beanName,Class<T> clazz) {
        Object o = beans.get(beanName);
        T cast = clazz.cast(o);
        return cast;
    }


    public static Object getByBeanName(String beanName) {
        Object o = beans.get(beanName);
        return o;
    }


}
